using System;
using System.IO;

namespace AntsMap
{
	/// <summary>
	/// Summary description for CostMap.
	/// </summary>
	public class CostMap
	{
		// The costs is a 3-d array.  A D-dimensional, E-elemental MAP
		// is stored as a Ex(D-1)xE array.
		//
		private int[,,] costs;
		private string testfile;
		private int dimension;
		private int elements;

		public CostMap()
		{
			this.testfile = null;
		}

		public CostMap( string testproblem )
		{
			this.testfile = testproblem;
		}
		

		// Accessor/modifier for the testfile string
		public string Testfile
		{
			get
			{
				return testfile;
			}
			set
			{
				testfile = value;
			}
		}

		public int Dimension
		{
			get
			{
				return dimension;
			}
		}

		public int Elements
		{
			get
			{
				return elements;
			}

		}
		
		public int BuildCostMap( )
		{
			StreamReader reader;
			string s = null;
			int i = 0;
			int j = 0;
			int k = 0;


			reader = File.OpenText( testfile );
			
			// We know the structure of these testfiles
			// The first line is dimension, second line has elements.
			// Also, our MAP is balanced, so we only read the first #elements
			s = reader.ReadLine();
			if( s != null )
				this.dimension = Convert.ToInt32( s );
			s = reader.ReadLine();
			if( s != null )
				this.elements = Convert.ToInt32( s.Substring(0,2).Trim() );
			
			// code really only works for 3DAP for now
			// 2D array maps like this: r(#c) + c
			if( this.dimension != 0 && this.elements != 0 )
				this.costs = new int [ this.elements, this.elements, this.elements ];
			else
				return -1;

			// Now read all cost values
			s = reader.ReadLine();
			while( s != null )
			{
				int cost = Convert.ToInt32( s );
				costs[i,j,k] = cost;
				k++;

				if( k == (this.elements))
				{
					k = 0;
					j++;
				}
				if( j == (this.elements))
				{
					j = 0;
					i++;
				}
				s = reader.ReadLine();
			}
			reader.Close();

			return 0;
		}

		public void AddItem( int item )
		{
		}
		
		public int Cost( int[,] solution )
		{
			int cost = 0;
			for( int i=0; i < this.Elements; i++)
				cost += costs[ solution[i,0],solution[i,1],solution[i,2]];

			return cost;

		}

        // TODO - only works with 3DAP for now
		public int Cost( int i, int j, int k )
		{
			return costs[ i , j , k ];
		}
	}
}
